package com.lzy.cloud.base.config;

/**
 * Created with IntelliJ IDEA.
 * Description: lzy-cloud-service
 *
 * @author: ellengou
 * @date: 2018-05-22 星期二
 * @time: 17:40
 */
import com.lzy.framework.core.exceptions.ExceptionDefinitions;
import com.lzy.framework.core.exceptions.XBusinessException;
import com.lzy.framework.core.output.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
@ResponseBody
@Configuration
public class GlobalExceptionHandler {

    Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 全局异常定义
     * @return
     */
    @Bean
    public ExceptionDefinitions getExceptionDefinitions(){
        ExceptionDefinitions exceptionDefinitions = new ExceptionDefinitions();
        return exceptionDefinitions;
    }

    /**
     * 業務异常报错
     * @param request
     * @param exception
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value=XBusinessException.class)
    public Result allXExceptionHandler(HttpServletRequest request,
                                       XBusinessException exception) {
        logger.error(exception.getMessage());
        exception.printStackTrace();
        return new Result(exception.getXCode(),exception.getMessageWithoutCode());
    }

    /**
     * 所有异常报错
     * @param request
     * @param exception
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value=Exception.class)
    public Result allExceptionHandler(HttpServletRequest request,
                                      Exception exception) {
        logger.error(exception.getMessage());
        exception.printStackTrace();
        return new Result("00000001","未知异常");
    }

}